import store from '@/store';
import utils from "@common/utils/utils";

/**
 * 按钮权限指令
 */
export default {
    inserted(el, binding, vNode) {
        let value = binding.value;
        if (typeof value === 'undefined') {
            return;
        }
        if (typeof value === 'string' && utils.isEmpty(value)) {
            return;
        }
        const application = store.state.application;
        let replaceBtnPermission = {};
        if (utils.isNotEmpty(application)) {
            const applicationStore = store.state[application];
            if (applicationStore && applicationStore.replaceBtnPermission) {
                replaceBtnPermission = applicationStore.replaceBtnPermission;
            }
        }
        let routerMenu = store.getters.getMenuByPath(vNode.context.$route.path);
        let checkPermission = [];
        if (vNode.context.$XEUtils.isPlainObject(value) && utils.isNotEmpty(value.permission)) {
            checkPermission = value.permission.split('|');
            if (utils.isNotEmpty(value.check_router)) {
                routerMenu = store.getters.getMenuByPath(value.check_router);
            }
        }
        if (vNode.context.$XEUtils.isString(value) && utils.isNotEmpty(value)) {
            checkPermission = value.split('|');
        }
        if (utils.isNotEmptyList(checkPermission)) {
            checkPermission = checkPermission.map(p => replaceBtnPermission[p] ? replaceBtnPermission[p] : p);
        }
        let routePermission = (routerMenu.childrens || []).map(item => $.extend({}, item));
        if (utils.isNotEmptyList(routePermission)) {
            let filter = routePermission.filter(item => checkPermission.indexOf(item.permission) !== -1);
            if (!utils.isNotEmptyList(filter)) {
                el.remove();
            }
        } else {
            el.remove();
        }
    },
};
